#!/bin/bash
# SmartInput 统一管理脚本
# 整合所有服务的管理功能

# 获取脚本所在目录的绝对路径
BASEDIR="$(cd "$(dirname "$0")" && pwd)"

# 日志目录
LOG_DIR="$BASEDIR/logs"
mkdir -p "$LOG_DIR"

# 日志函数
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_DIR/system.log"
}

# 显示帮助信息
show_help() {
    echo "🚀 SmartInput 统一管理工具"
    echo "=========================="
    echo "用法: $0 [服务] [命令]"
    echo ""
    echo "服务:"
    echo "  all       - 所有服务 (后端+前端+手机端)"
    echo "  backend   - 后端服务"
    echo "  frontend  - 前端服务"
    echo "  mobile    - 手机端服务"
    echo ""
    echo "命令:"
    echo "  start     - 启动服务"
    echo "  stop      - 停止服务"
    echo "  restart   - 重启服务"
    echo "  status    - 查看状态"
    echo "  logs      - 查看日志"
    echo "  test      - 测试功能"
    echo "  help      - 显示帮助"
    echo ""
    echo "示例:"
    echo "  $0 all start      # 启动所有服务"
    echo "  $0 mobile start   # 启动手机端"
    echo "  $0 all status     # 查看所有服务状态"
    echo "  $0 mobile logs    # 查看手机端日志"
    echo ""
    echo "💡 快捷命令:"
    echo "  $0 start          # 启动所有服务"
    echo "  $0 stop           # 停止所有服务"
    echo "  $0 status         # 查看所有服务状态"
    echo "  $0 logs           # 查看所有日志"
    echo ""
    echo "🔒 HTTPS说明:"
    echo "  - 已自动生成自签名证书，证书文件位于 certs/ 目录。"
    echo "  - 后端HTTPS端口: 8443，前端/手机端HTTPS端口同HTTP。"
    echo "  - 浏览器首次访问需信任自签名证书，详见README.md。"
}

# 检查服务是否运行
check_service() {
    local service="$1"
    local pid_file="$LOG_DIR/${service}.pid"
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null 2>&1; then
            return 0
        fi
    fi
    return 1
}

# 启动后端服务
start_backend() {
    log "[后端] 启动服务..."
    cd "$BASEDIR/backend"
    
    # 检查Java环境
    if ! command -v java &> /dev/null; then
        log "[后端] ❌ Java 未安装，请先安装 Java 21+"
        return 1
    fi
    
    # 构建项目
    if ! mvn clean install > "$LOG_DIR/backend.log" 2>&1; then
        log "[后端] ❌ 构建失败，请查看日志: $LOG_DIR/backend.log"
        return 1
    fi
    
    # 启动服务前清空日志
    > "$LOG_DIR/backend.log"
    nohup mvn spring-boot:run > "$LOG_DIR/backend.log" 2>&1 &
    local pid=$!
    echo $pid > "$LOG_DIR/backend.pid"
    log "[后端] 进程已启动，PID: $pid"
    
    # 等待启动
    sleep 10
    if curl -f http://localhost:8080/actuator/health > /dev/null 2>&1; then
        log "[后端] ✅ 服务启动成功，端口: 8080"
    else
        log "[后端] ⚠️  服务可能未完全启动"
    fi
}

# 启动前端服务
start_frontend() {
    log "[前端] 启动服务..."
    cd "$BASEDIR/frontend"
    
    # 检查Node.js环境
    if ! command -v npm &> /dev/null; then
        log "[前端] ❌ npm 未安装，请先安装 Node.js"
        return 1
    fi
    
    # 安装依赖
    if [ ! -d "node_modules" ]; then
        log "[前端] 安装依赖..."
        npm install > "$LOG_DIR/frontend.log" 2>&1
    fi
    
    # 启动服务前清空日志
    > "$LOG_DIR/frontend.log"
    nohup npm run dev > "$LOG_DIR/frontend.log" 2>&1 &
    local pid=$!
    echo $pid > "$LOG_DIR/frontend.pid"
    log "[前端] 进程已启动，PID: $pid"
    
    # 等待启动
    sleep 5
    if curl -f http://localhost:5173 > /dev/null 2>&1; then
        log "[前端] ✅ 服务启动成功，端口: 5173"
    else
        log "[前端] ⚠️  服务可能未完全启动"
    fi
}

# 启动手机端服务
start_mobile() {
    log "[手机端] 启动服务..."
    cd "$BASEDIR/mobile-app"
    
    # 检查Node.js环境
    if ! command -v npm &> /dev/null; then
        log "[手机端] ❌ npm 未安装，请先安装 Node.js"
        return 1
    fi
    
    # 检查package.json
    if [ ! -f "package.json" ]; then
        log "[手机端] ❌ package.json 文件不存在"
        return 1
    fi
    
    # 安装依赖
    if [ ! -d "node_modules" ]; then
        log "[手机端] 安装依赖..."
        npm install > "$LOG_DIR/mobile.log" 2>&1
    fi
    
    # 启动服务前清空日志
    > "$LOG_DIR/mobile.log"
    nohup npm run dev > "$LOG_DIR/mobile.log" 2>&1 &
    local pid=$!
    echo $pid > "$LOG_DIR/mobile.pid"
    log "[手机端] 进程已启动，PID: $pid"
    
    # 等待启动
    sleep 8
    if curl -f http://localhost:3001 > /dev/null 2>&1; then
        log "[手机端] ✅ 服务启动成功，端口: 3001"
    else
        log "[手机端] ⚠️  服务可能未完全启动"
    fi
}

# 停止服务
stop_service() {
    local service="$1"
    local pid_file="$LOG_DIR/${service}.pid"
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null 2>&1; then
            log "[$service] 停止进程 $pid ..."
            kill $pid
            sleep 2
            if ps -p $pid > /dev/null 2>&1; then
                log "[$service] 强制终止进程 $pid ..."
                kill -9 $pid
            fi
            log "[$service] ✅ 已停止"
        else
            log "[$service] ⚠️  进程 $pid 不存在"
        fi
        rm -f "$pid_file"
    else
        log "[$service] ℹ️  PID 文件不存在"
    fi
    # 前端服务时，自动释放 5173 端口
    if [ "$service" = "frontend" ]; then
        if command -v fuser &> /dev/null; then
            fuser -k 5173/tcp || true
            log "[前端] 已自动释放 5173 端口"
        fi
    fi
}

# 查看服务状态
show_status() {
    local service="$1"
    
    if [ "$service" = "all" ]; then
        echo "========== SmartInput 服务状态 =========="
        show_service_status "backend" "后端" "8080"
        show_service_status "frontend" "前端" "5173"
        show_service_status "mobile" "手机端" "3001"
        echo ""
        echo "========== 访问地址 =========="
        echo "🔧 管理后台: http://localhost:5173"
        echo "📱 手机端应用: http://localhost:3001"
        echo "🔌 后端API: http://localhost:8080"
        if [ -f "$BASEDIR/certs/smartinput.p12" ]; then
            echo "🔒 后端HTTPS: https://localhost:8443 (自签名证书)"
        fi
        if [ -f "$BASEDIR/certs/smartinput.key" ] && [ -f "$BASEDIR/certs/smartinput.crt" ]; then
            echo "🔒 前端HTTPS: https://localhost:5173 (自签名证书)"
            echo "�� 手机端HTTPS: https://localhost:3001 (自签名证书)"
        fi
        return
    else
        show_service_status "$service" "$2" "$3"
    fi
}

# 显示单个服务状态
show_service_status() {
    local service="$1"
    local name="$2"
    local port="$3"
    local pid_file="$LOG_DIR/${service}.pid"
    
    echo "[$name] 状态:"
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null 2>&1; then
            echo "  ✅ 进程运行中 (PID: $pid)"
            if lsof -i :$port | grep LISTEN > /dev/null; then
                echo "  ✅ 端口 $port 可访问"
            else
                echo "  ⚠️  端口 $port 未监听"
            fi
        else
            echo "  ❌ 进程不存在 (PID: $pid)"
        fi
    else
        echo "  ℹ️  PID 文件不存在"
    fi
}

# 查看日志
view_logs() {
    local service="$1"
    local log_file="$LOG_DIR/${service}.log"
    
    if [ "$service" = "all" ]; then
        echo "========== 所有服务日志 =========="
        for s in backend frontend mobile; do
            local log="$LOG_DIR/${s}.log"
            if [ -f "$log" ]; then
                echo "📄 $s 日志 (最后20行):"
                echo "=================================="
                tail -20 "$log"
                echo ""
            fi
        done
    else
        if [ -f "$log_file" ]; then
            echo "📄 $service 日志 (最后50行):"
            echo "=================================="
            tail -50 "$log_file"
        else
            echo "⚠️  日志文件不存在: $log_file"
        fi
    fi
}

# 测试功能
test_service() {
    local service="$1"
    
    if [ "$service" = "all" ]; then
        log "🧪 测试所有服务..."
        # 这里可以添加集成测试
        echo "✅ 所有服务测试完成"
    else
        log "🧪 测试 $service 服务..."
        # 这里可以添加具体服务的测试
        echo "✅ $service 服务测试完成"
    fi
}

# 主逻辑
main() {
    local service="${1:-all}"
    local command="${2:-start}"
    
    # 快捷命令处理
    if [ "$service" = "start" ] || [ "$service" = "stop" ] || [ "$service" = "status" ] || [ "$service" = "logs" ]; then
        command="$service"
        service="all"
    fi
    
    case "$service" in
        "all")
            case "$command" in
                "start")
                    log "========== 启动 SmartInput 所有服务 =========="
                    start_backend
                    start_frontend
                    start_mobile
                    log "========== 所有服务启动完成 =========="
                    ;;
                "stop")
                    log "========== 停止 SmartInput 所有服务 =========="
                    stop_service "backend"
                    stop_service "frontend"
                    stop_service "mobile"
                    log "========== 所有服务已停止 =========="
                    ;;
                "restart")
                    log "========== 重启 SmartInput 所有服务 =========="
                    stop_service "backend"
                    stop_service "frontend"
                    stop_service "mobile"
                    sleep 3
                    start_backend
                    start_frontend
                    start_mobile
                    log "========== 所有服务重启完成 =========="
                    ;;
                "status")
                    show_status "all"
                    ;;
                "logs")
                    view_logs "all"
                    ;;
                "test")
                    test_service "all"
                    ;;
                *)
                    show_help
                    ;;
            esac
            ;;
        "backend")
            case "$command" in
                "start") start_backend ;;
                "stop") stop_service "backend" ;;
                "restart")
                    stop_service "backend"
                    sleep 2
                    start_backend
                    ;;
                "status") show_status "backend" "后端" "8080" ;;
                "logs") view_logs "backend" ;;
                "test") test_service "backend" ;;
                *) show_help ;;
            esac
            ;;
        "frontend")
            case "$command" in
                "start") start_frontend ;;
                "stop") stop_service "frontend" ;;
                "restart")
                    stop_service "frontend"
                    sleep 2
                    start_frontend
                    ;;
                "status") show_status "frontend" "前端" "5173" ;;
                "logs") view_logs "frontend" ;;
                "test") test_service "frontend" ;;
                *) show_help ;;
            esac
            ;;
        "mobile")
            case "$command" in
                "start") start_mobile ;;
                "stop") stop_service "mobile" ;;
                "restart")
                    stop_service "mobile"
                    sleep 2
                    start_mobile
                    ;;
                "status") show_status "mobile" "手机端" "3001" ;;
                "logs") view_logs "mobile" ;;
                "test") test_service "mobile" ;;
                *) show_help ;;
            esac
            ;;
        "help"|*)
            show_help
            ;;
    esac
}

# 运行主函数
main "$@" 